//
//  ChatViewController.m
//  XRSquare
//
//  Created by UaenaMo on 2018/8/16.
//  Copyright © 2018年 UaenaMo. All rights reserved.
//

#import "ChatViewController.h"
#import "ChatOptionView.h"
#import "ChatBubbleTableViewCell.h"
#import "JSONKit.h"
@interface ChatViewController ()<UITableViewDelegate,UITableViewDataSource,ChatOptionViewDelegate,ChatBubbleTableViewCellDelegate>
{
    UITableView * chatTabelView;
    ChatOptionView * optionView;
    NSArray * chatData;
    
    NSString * selfPic;
    NSTimer * timer;

}
@end

@implementation ChatViewController

-(instancetype)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
{
    if (self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil]) {
        self.contentid = @"";
    }
    return self;
}

-(void)viewWillDisappear:(BOOL)animated
{
    [super viewWillDisappear:animated];
    [timer invalidate];
}

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.

    //滚动 tableView 到底，确保只执行一次。
    self.isScrollBottom = NO;

    [self layoutContent];
    [self layoutConntentView];
    [self checkConversationType];
    [self requestData];
    [self addKeyboardNotifications];
    timer = [NSTimer scheduledTimerWithTimeInterval:0.5 target:self selector:@selector(requestData) userInfo:nil repeats:YES];
}

-(void)addKeyboardNotifications
{
    [[NSNotificationCenter defaultCenter] addObserver:self
     
                                             selector:@selector(keyboardWasShown:)
     
                                                 name:UIKeyboardWillShowNotification object:nil];
    
    [[NSNotificationCenter defaultCenter] addObserver:self
     
                                             selector:@selector(keyboardWillBeHidden:)
     
                                                 name:UIKeyboardWillHideNotification object:nil];
    
}

- (void)keyboardWasShown:(NSNotification*)aNotification
{
    NSDictionary* info = [aNotification userInfo];
    CGSize kbSize = [[info objectForKey:UIKeyboardFrameEndUserInfoKey] CGRectValue].size;//得到鍵盤的高度
//    NSLog(@"hight_hitht:%f",kbSize.height);

    //键盘弹出，更新 tableView 高度，并且滚动到底
    chatTabelView.frame = CGRectMake(chatTabelView.frame.origin.x, chatTabelView.frame.origin.y, chatTabelView.frame.size.width, chatTabelView.frame.size.height - kbSize.height);
    [chatTabelView scrollToRowAtIndexPath:[NSIndexPath indexPathForRow:chatData.count-1 inSection:0] atScrollPosition:UITableViewScrollPositionNone animated:NO];

    optionView.frame = CGRectMake(0, ScreenHeight - 45 - kbSize.height, ScreenWidth, 45);
    optionView.kbHeight = kbSize.height;
}

- (void)keyboardWillBeHidden:(NSNotification*)aNotification
{
    //键盘收起，更新 tab 高度
    CGRect rectStatus = [[UIApplication sharedApplication] statusBarFrame];
    CGRect rectNav = self.navigationController.navigationBar.frame;
    chatTabelView.frame = CGRectMake(chatTabelView.frame.origin.x, chatTabelView.frame.origin.y, chatTabelView.frame.size.width, ScreenHeight - rectStatus.size.height - rectNav.size.height - 45);

    optionView.frame = CGRectMake(0, ScreenHeight - 45, ScreenWidth, 45);
    optionView.kbHeight = 0;
}

-(void)requestData
{
    [NetRequestCenter privatedetailwithgroupid:self.contentid tid:@"" result:^(BOOL success, NSDictionary *resultDic) {
        if (success)
        {
            selfPic = [[[[resultDic objectForKey:@"data"] objectForKey:@"Detail"]objectForKey:@"UserInfo"]objectForKey:@"headPic"];
            
            NSArray * newchatData = [[[resultDic objectForKey:@"data"] objectForKey:@"Detail"]objectForKey:@"content"
                                     ];
            if ([newchatData count] != [chatData count])
            {
                chatData = newchatData;
                [chatTabelView reloadData];
            }
        }
    }];
}

-(void)checkConversationType
{

}

-(void)backAction
{
    [self.navigationController popViewControllerAnimated:YES];
}

-(void)layoutContent
{
    self.view.backgroundColor = [UIColor whiteColor];
    self.navigationController.navigationBarHidden = NO;
    self.navigationController.navigationBar.tintColor = [UIColor grayColor];
    
    self.navigationItem.leftBarButtonItem = [[UIBarButtonItem alloc] initWithImage:[[UIImage imageNamed:@"back"] imageWithRenderingMode:UIImageRenderingModeAlwaysTemplate] style:UIBarButtonItemStylePlain target:self action:@selector(backAction)];
    
    CGRect rectStatus = [[UIApplication sharedApplication] statusBarFrame];
    CGRect rectNav = self.navigationController.navigationBar.frame;
    self.navigationItem.title = self.targetName;
}

-(void)layoutConntentView
{
    CGRect rectStatus = [[UIApplication sharedApplication] statusBarFrame];
    CGRect rectNav = self.navigationController.navigationBar.frame;
    
    chatTabelView = [[UITableView alloc]initWithFrame:CGRectMake(0, rectStatus.size.height + rectNav.size.height, ScreenWidth, ScreenHeight - rectStatus.size.height - rectNav.size.height - 45) style:UITableViewStylePlain]; // 需要额外减掉输入框高度
    chatTabelView.delegate = self;
    chatTabelView.dataSource = self;
//    chatTabelView.keyboardDismissMode = UIScrollViewKeyboardDismissModeOnDrag;
//    chatTabelView.backgroundColor = [UIColor colorFromHexCode:@"f5f5f5"];
    if (@available(iOS 11.0, *)) {
        chatTabelView.contentInsetAdjustmentBehavior = UIScrollViewContentInsetAdjustmentNever;
    } else {
        // Fallback on earlier versions
    }
    chatTabelView.separatorStyle = UITableViewCellSeparatorStyleNone;


    [self.view addSubview:chatTabelView];
    
    UITapGestureRecognizer * tap = [[UITapGestureRecognizer alloc]initWithTarget:self action:@selector(cancleEdit)];
    [chatTabelView addGestureRecognizer:tap];
    
    optionView = [ChatOptionView optionView];
    optionView.delegate = self;
    [self.view addSubview:optionView];
}

-(void)cancleEdit
{
    [optionView dismiss];
}

-(NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    return [chatData count];
}

-(CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    NSString * chatStr = [[chatData objectAtIndex:indexPath.row]objectForKey:@"Content"];
    return [ChatBubbleTableViewCell heightWithContentText:chatStr];
}

-(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    static NSString * identifer = @"top";
    ChatBubbleTableViewCell * cell = [tableView dequeueReusableCellWithIdentifier:identifer];
    if (!cell) {
        cell = [[ChatBubbleTableViewCell alloc]initWithStyle:UITableViewCellStyleDefault reuseIdentifier:identifer];
    }
    NSDictionary * dic = [chatData objectAtIndex:indexPath.row];
    NSString * chatStr = [[chatData objectAtIndex:indexPath.row]objectForKey:@"Content"];
    [cell loadData:chatStr];
    if ([[dic objectForKey:@"TalkerUid"] isEqualToString:self.targetUid])
    {
        [cell loadUserData:self.targetPic left:YES];
    }
    else
    {
        [cell loadUserData:selfPic left:NO];
    }
    return cell;
}

-(BOOL)tableView:(UITableView *)tableView shouldHighlightRowAtIndexPath:(NSIndexPath *)indexPath
{
    return NO;
}

-(void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    
}
//首次渲染界面，tableView 滚动到底
-(void)tableView:(UITableView *)tableView willDisplayCell:(UITableViewCell *)cell forRowAtIndexPath:(NSIndexPath *)indexPath
{
    if (self.isScrollBottom == NO) {

        [chatTabelView scrollToRowAtIndexPath:[NSIndexPath indexPathForRow:chatData.count-1 inSection:0] atScrollPosition:UITableViewScrollPositionNone animated:NO];

        if (indexPath.row == chatData.count-1) {

            self.isScrollBottom = YES;
        }

    }
}

-(void)inputText:(NSString *)text
{
    [NetRequestCenter writeprivatewithuid:self.targetUid content:text result:^(BOOL success, NSDictionary *resultDic) {
        if (success)
        {
            self.isScrollBottom = NO;
            self.contentid = [[resultDic objectForKey:@"data"]objectForKey:@"GroupID"];
        }
    }];
}

-(void)inputAudio:(NSString *)audioPath
{
 
}

-(void)selectImage
{
    
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
 #pragma mark - Navigation
 
 // In a storyboard-based application, you will often want to do a little preparation before navigation
 - (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
 // Get the new view controller using [segue destinationViewController].
 // Pass the selected object to the new view controller.
 }
 */

@end
